package org.wsiz.vro.web.domain;

import static org.wsiz.vro.domain.Film_.*;
import static com.google.common.collect.Lists.newArrayList;
import java.io.Serializable;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Component;
import org.wsiz.vro.domain.Film;
import org.wsiz.vro.repository.FilmRepository;
import org.wsiz.vro.repository.support.Range;
import org.wsiz.vro.repository.support.Ranges.RangeInteger;
import org.wsiz.vro.web.domain.support.GenericSearchForm;

/**
 * SearchForm for {@link Film}
 */
@Component
@Scope("session")
public class FilmSearchForm extends GenericSearchForm<Film> implements Serializable {
    private static final long serialVersionUID = 1L;
    // make it static to avoid http://jira.springframework.org/browse/SWF-1224
    private static FilmRepository filmRepository;

    private Film film = new Film();
    private RangeInteger<Film> yearRange = new RangeInteger<Film>(year);

    @Autowired
    public FilmSearchForm(FilmRepository instance) {
        if (filmRepository == null) {
            filmRepository = instance;
        }
    }

    /**
     * Server side pagination with lazy model.
     * Automatically called by PrimeFaces component (via the GenericSearchForm).
     */
    @Override
    protected List<Film> load(PageRequest pageRequest) {
        List<Range<Film, ?>> ranges = newArrayList();
        ranges.add(yearRange);

        Page<Film> page = filmRepository.findWithExample(film, ranges, pageRequest);
        setRowCount((int) page.getTotalElements());
        return page.getContent();
    }

    /**
     * The root film for search by example.
     * Used from the view.
     */
    public Film getFilm() {
        return film;
    }

    // Ranges, used from the view.

    public RangeInteger<Film> getYearRange() {
        return yearRange;
    }
}